# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggplot2)
library(ggrepel)
library(dplyr)
library(tidyr)
library(tibble)
library(ropls)
library(optparse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

inputData <- read.csv(opt$i, header = T, check.names = F, stringsAsFactors = F)

options(digits = 3)

sampleIds <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  .$SampleID

tmpData <- inputData %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  select(c("Metabolite", sampleIds))

data <- tmpData %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID"))

classNotes <- unique(sampleInfo$ClassNote)
cn <- combn(classNotes, 2)
for (i in 1:ncol(cn)) {
  load("oplsda.RData")

  method <- "pearson"
  pData <- plsdaRs@suppLs[["xModelMN"]] %>%
    as.data.frame() %>%
    summarise_all(function(x) { cor.test(x, plsdaRs@scoreMN, method = method)$p.value }) %>%
    unlist()
  vipVn = getVipVn(plsdaRs)
  corData <- cor(plsdaRs@suppLs[["xModelMN"]], plsdaRs@scoreMN, method = method) %>%
    as.data.frame() %>%
    .$p1

  classData <- inputData %>%
    select(c("Class", "Metabolite", "HMDB"))
  vipData <- data.frame(VIP = vipVn, Corr.Coeffs. = corData, P = pData) %>%
    rownames_to_column("Metabolite")
  allData <- classData %>%
    inner_join(vipData, by = c("Metabolite")) %>%
    mutate(FDR = p.adjust(P, method = "fdr")) %>%
    arrange(desc(VIP))
  parent <- "./"
  createWhenNoExist(parent)
  allFileName <- paste0(parent, "/OPLSDA_VIP.csv")
  write.csv(allData, allFileName, row.names = FALSE)
}







